import http from '@/utils/http'
import store, { AppDispatch } from '..'
/**
 * 获取文章新闻推荐
 * @param channel_id 频道ID
 * @param timestamp  时间戳，请求新的推荐数据传当前的时间戳，请求历史推荐传指定的时间戳
 * @returns {Promise} Promise<void>
 */
export const getArticles = ({
  channel_id = 0,
  timestamp = Date.now(),
  isRefresh = false,
}) => {
  return async (dispatch: AppDispatch) => {
    const res = await http.get(`/v1_0/articles`, {
      params: { channel_id, timestamp },
    })
    const { articles } = store.getState().article
    // console.log('action内部1', articles)
    const list = articles[channel_id]?.list
    const pre_timestamp = res.data.pre_timestamp
    //情况1：如果没有列表就直接存
    if (!list || isRefresh) {
      dispatch({
        type: 'article/saveArticles',
        // 存储多个频道数据
        payload: {
          ...articles,
          // 🎯 注意这里要设置动态的频道 id，需要使用方括号[]语法动态设置键名称
          [channel_id]: {
            timestamp: pre_timestamp,
            list: res.data.results,
          },
        },
      })
    } else {
      //情况2：如果有列表则追加
      dispatch({
        type: 'article/saveArticles',
        // 存储多个频道数据
        payload: {
          ...articles,
          // 🎯 注意这里要设置动态的频道 id，需要使用方括号[]语法动态设置键名称
          [channel_id]: {
            timestamp: pre_timestamp,
            list: [...list, ...res.data.results],
          },
        },
      })
    }
    if (!pre_timestamp) {
      //没有更多数据
      return Promise.reject('没有推荐了')
    }
  }
}

/**
 * 文章标记 -  文章不感兴趣和举报
 * @param visible     用于控制标记弹窗的显示与隐藏
 * @param article_id  需要标记的文章 id
 * @returns
 */
export const setArticleMark = ({ visible = false, article_id = '' }) => {
  return async (dispatch: AppDispatch) => {
    dispatch({ type: 'article/setMark', payload: { visible, article_id } })
  }
}
/**
 * 不感兴趣
 * @param target
 * @returns
 */
export const setArticleDislikes = (target: string) => {
  return async (dispatch: AppDispatch) => {
    const res = await http.post(`/v1_0/article/dislikes`, { target })
    console.log(`/v1_0/article/dislikes`, res)

    // 从 redux 把当前文章删除
    // 获取当前频道 id
    const activeId = store.getState().channel.activeId
    // // 根据频道 id 获取文章列表
    const articles = store.getState().article.articles
    // const { channel: { activeId }, article: { articles } } = store.getState()
    // 根据频道 id 获取文章列表
    const { list, timestamp } = articles[activeId]
    // console.log({ list, timestamp })
    dispatch({
      type: 'article/saveArticles',
      payload: {
        // 保留其他频道的数据
        ...articles,
        // 当前频道的不喜欢的那条文章过滤掉
        [activeId]: {
          timestamp,
          list: list.filter((v) => v.art_id !== target),
        },
      },
    })
  }
}

/**
 * 举报文章
 * @param  target 举报文章id
 * @param  type 举报类型
 * @param  remark  举报附加说明
 * @returns
 */
export const setArticleReports = ({ target = '', type = '0', remark = '' }) => {
  return async (dispatch: AppDispatch) => {
    const res = await http.post(`/v1_0/article/reports`, {
      target,
      type,
      remark,
    })
    console.log(`/v1_0/article/reports`, res)

    // 从 redux 把当前文章删除
    // 获取当前频道 id
    const activeId = store.getState().channel.activeId
    // // 根据频道 id 获取文章列表
    const articles = store.getState().article.articles
    // const { channel: { activeId }, article: { articles } } = store.getState()
    // 根据频道 id 获取文章列表
    const { list, timestamp } = articles[activeId]
    // console.log({ list, timestamp })
    dispatch({
      type: 'article/saveArticles',
      payload: {
        // 保留其他频道的数据
        ...articles,
        // 当前频道的不喜欢的那条文章过滤掉
        [activeId]: {
          timestamp,
          list: list.filter((v) => v.art_id !== target),
        },
      },
    })
  }
}

/**
 * 获取新闻详情
 * @param article_id 文章id
 * @returns
 */
export const getArticleDetail = (article_id: string) => {
  return async (dispatch: AppDispatch) => {
    const res = await http.get(`/v1_0/articles/${article_id}`)
    console.log(`/v1_0/articles/${article_id}`, res)
    dispatch({ type: 'article/saveDetail', payload: res.data })
  }
}

/**
 * 点赞和取消点赞
 * @param target 文章id
 * @returns
 */
export const changeArticleLikings = (target: string) => {
  return async (dispatch: AppDispatch) => {
    // 	用户对文章的态度, -1: 无态度，0-不喜欢，1-点赞
    const { detail } = store.getState().article
    if (detail.attitude !== 1) {
      // 情况1：点赞
      await http.post(`/v1_0/article/likings`, { target })
      // console.log(res)
      dispatch({
        type: 'article/saveDetail',
        payload: { ...detail, attitude: 1 },
      })
    } else {
      // 情况2：取消点赞
      await http.delete(`/v1_0/article/likings/${target}`)
      // console.log(res)
      dispatch({
        type: 'article/saveDetail',
        payload: { ...detail, attitude: -1 },
      })
    }
  }
}
